﻿using ConfigInfoWebPlatform.API.BusinessCommon;
using ConfigInfoWebPlatform.API.DBCommon;
using ConfigInfoWebPlatform.API.ViewModel;
using ConfigInfoWebPlatform.Model;
using ConfigInfoWebPlatform.Nlog;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.Controllers
{
    /// <summary>
    /// 角色
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        readonly LogHelper _log;
        readonly string configRootPath;

        /// <summary>
        /// 实例化构造函数
        /// </summary>
        public RoleController(LogHelper logHelper, IConfiguration configuration)
        {
            _log = logHelper;
            configRootPath = configuration["AppSetting:configPath"].ToString();
        }

        /// <summary>
        /// 分页获取角色数据
        /// </summary>
        [HttpGet("index")]
        public IActionResult Index(int page,int limit,string name)
        {
            //获取当前登录用户信息
            UserInfoModel identity = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            identity = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);

            List<RoleInfoModel> roleList = new List<RoleInfoModel>();
            DAL_Role roleDal = new DAL_Role();
            roleList = roleDal.GetRoleList(name, identity.D_id, identity.Name == "admin" ? true : false);
            var resultList = roleList.Skip((page - 1) * limit).Take(limit).ToList();
            return new JsonResult(new
            {
                code = 0,
                msg="success",
                count=roleList.Count,
                data=resultList
            });
        }

        /// <summary>
        /// 获取所有权限数据
        /// </summary>
        [HttpGet("getauthoritytree")]
        public IActionResult GetAuthorityTree(string rid)
        {
            DAL_ProgramNavicat _programNavicat = new DAL_ProgramNavicat();
            var programNavicats = _programNavicat.GetProgramNavicatInfos();
            List<long> checkedIdList = new List<long>();
            var firstNavs = programNavicats.Where(x => x.Level == 1)
                                            .Select(x => new ProgramNavicatTreeModel()
                                            {
                                                Id = x.ID,
                                                Name = x.Name,
                                            }).ToList();
            foreach (var first in firstNavs)
            {
                GetProgramNavicatChilder(programNavicats,first);
            }                                                            
            DAL_Role roleDal = new DAL_Role();
            checkedIdList = roleDal.GetProgramNavicatIds(rid);
            var parentIds = roleDal.GetprogramNavicatPids(rid);
            checkedIdList = checkedIdList.Where(x => !parentIds.Contains(x)).ToList();
            var checkedIds = checkedIdList.ToArray();
            return new JsonResult(new
            {
                code = 0,
                msg = "success",
                checkedIds = checkedIds,
                data = firstNavs
            });

        }
        private void GetProgramNavicatChilder(List<ProgramNavicatModel> allNavs, ProgramNavicatTreeModel parent)
        {
            DAL_Role roleDal = new DAL_Role();
            if (parent!=null)
            {
                var childers = allNavs.Where(x => x.ParentId == parent.Id && x.Code != "navicatadmin").ToList();
               
                if (childers.Any())
                {
                    parent.Childrens = childers.Select(x => new ProgramNavicatTreeModel()
                    {
                        Id = x.ID,
                        Name = x.Name,
                    }).ToList();
                    foreach (var nav in parent.Childrens)
                    {
                        GetProgramNavicatChilder(allNavs, nav);
                    }
                }
            }
        }

        /// <summary>
        /// 保存角色权限数据
        /// </summary>
        [HttpPost("saveroleauthority")]
        public IActionResult SaveRoleAuthority([FromBody]RoleAuthoritySaveModel model)
        {
            //删除角色所有应权限  
            DAL_Role roleDal = new DAL_Role();
            var delResult = roleDal.DeleteRoleAuthority(model.RId);
            int resultCode = 0;
            if (model.IsClearAll == 0)
            {
                //添加角色权限
                for (int i = 0; i < model.AIds.Count; i++)
                {
                    Authority authority = new Authority();
                    authority.Id = $"{model.RId}{(i + 1).ToString().PadLeft(4, '0')}";
                    authority.PNId = model.AIds[i].ToString();
                    authority.RId = model.RId;
                    roleDal.InsertRoleAuthority(authority);
                }
            }
            //角色菜单权限Id数据
            var checkedIdList = roleDal.GetProgramNavicatIds(model.RId);
            var parentIds = roleDal.GetprogramNavicatPids(model.RId);
            checkedIdList = checkedIdList.Where(x => !parentIds.Contains(x)).ToList();
            var checkedIds = checkedIdList.ToArray();
            return new JsonResult(new
            {
                code = resultCode,
                msg = "success",
                data = checkedIds
            });
        }

        /// <summary>
        /// 获取角色详情数据
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public IActionResult Detail(string rid)
        {
            RoleModel role = new RoleModel();
            DAL_Role roleDal = new DAL_Role();
            role = roleDal.GetRoleDetail(rid);
            return new JsonResult(new { code = 0, msg = "success", data = role });
        }


        /// <summary>
        /// 根据角色Id删除角色信息
        /// </summary>
        [HttpPost("deleterole")]
        public IActionResult DeleteRole(string rid)
        {
            DAL_Role roleDal = new DAL_Role();
            //删除角色的权限数据
            roleDal.DeleteRoleAuthority(rid);
            //删除角色数据
            roleDal.DeleteRole(rid);
            return new JsonResult(new { code = 0, msg = "success" });
        }

        /// <summary>
        /// 保存角色数据
        /// </summary>
        [HttpPost("saverole")]
        public IActionResult SaveRole([FromBody]Role model)
        {
            DAL_Role roleDal = new DAL_Role();
            int result = 0;
            string resultMsg = "success";
            if (string.IsNullOrWhiteSpace(model.Id))
            {
                model.Id = Snowflake.Instance().GetId().ToString();
                if (!roleDal.IsExists(did:model.DId,code:model.Code))
                    result=roleDal.InsertRole(model);
                else
                    resultMsg = $"该部门下已存在Code为 {model.Code} 的角色";
            }
            else
            {
                var role = roleDal.GetRoleDetail(model.Id);
                if(role!=null && !string.IsNullOrWhiteSpace(role.Id))
                {
                    if (!roleDal.IsExists(model.Id, model.DId, model.Code))
                        result=roleDal.EditRole(model);
                    else
                        resultMsg = $"该部门下已存在Code为 {model.Code} 的角色";
                }
                else
                    resultMsg = $"此角色不存在或已删除";

            }
            return new JsonResult(new
            {
                code = result > 0 ? 0 : 1,
                msg = resultMsg
            });
        }

        /// <summary>
        /// 获取部门数据
        /// </summary>
        [HttpGet("getdepartments")]
        public IActionResult GetDepartments()
        {
            List<DepartmentModel> departments = new List<DepartmentModel>();
            DAL_Role roleDal = new DAL_Role();
            departments = roleDal.GetDepartments();
            return new JsonResult(new { code = 0, msg = "success", data = departments });
        }

    }
}
